package com.yexx.starter.security.pwd;

import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;

import java.util.Collection;

/**
 * Description: 自定义账户密码认证token
 *
 * @author: zuomin (myleszelic@outlook.com)
 * @date: 2020/11/03 10:56
 */
public class PwdAuthenticationToken extends AbstractAuthenticationToken {

    private static final long serialVersionUID = 2383092775910246006L;

    private String deviceUuid;
    private final String phoneNumber;
    private String pwd;

    public PwdAuthenticationToken(String phoneNumber, String pwd, String deviceUuid) {
        super(null);
        this.deviceUuid = deviceUuid;
        this.phoneNumber = phoneNumber;
        this.pwd = pwd;
        setAuthenticated(false);
    }

    public PwdAuthenticationToken(String phoneNumber, String pwd, String deviceUuid, Collection<? extends GrantedAuthority> authorities) {
        super(authorities);
        this.deviceUuid = deviceUuid;
        this.phoneNumber = phoneNumber;
        this.pwd = pwd;
        super.setAuthenticated(true);
    }

    @Override
    public Object getCredentials() {
        return this.pwd;
    }

    @Override
    public Object getPrincipal() {
        return this.phoneNumber;
    }

    @Override
    public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
        if (isAuthenticated) {
            throw new IllegalArgumentException("Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
        }
        super.setAuthenticated(false);
    }

    @Override
    public void eraseCredentials() {
        super.eraseCredentials();
        this.pwd = null;
    }

    public String getDeviceUuid() {
        return deviceUuid;
    }

}
